<script setup lang="tsx">
import { StepBackwardOutlined } from '@ant-design/icons-vue'
import { onMounted, ref } from 'vue';
import { type Fields } from './packages';
// import { VForm, VEditModal } from './packages'

const mockList = [
  {
    label: 'root 1',
    value: 'root 1',
    oneLevelName: '玉米',
    children: [
      {
        label: 'parent 1',
        value: 'parent 1',
        oneLevelName: '大米',
        children: [
          {
            label: 'parent 1-0',
            value: 'parent 1-0',
            oneLevelName: '红豆',
            children: [
              {
                label: 'my leaf',
                value: 'leaf1',
                oneLevelName: '绿豆'
              },
              {
                label: 'your leaf',
                value: 'leaf2',
                oneLevelName: '绿豆sadsa'
              },
            ],
          },
          {
            label: 'parent 1-1',
            value: 'parent 1-1',
            oneLevelName: '红sdad豆',
          },
        ],
      },
      {
        label: 'parent 2',
        value: 'parent 2',
      },
    ],
  },
]

const fields = ref<Fields[]>([
  {
    label: '变更单号',
    key: 'orderNumber',
    el: 'select',
    props: {
      placeholder: '请输入变更单号',
      options: [
        {
          label: '是',
          value: 1,
          oneLevelName: '玉米'
        },
        {
          label: '否',
          value: 0,
          oneLevelName: '小麦'
        }
      ],
      showSearch: true,
      filterOption: (input: string, option: any) => {
        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
    },
    renderSlots: {
      option: (option) => {
        return (
          <>
            <span style="float: left"> {option.label} </span>
            <span class="float-right text-[13px] text-[#909399]">
              作物：{option.oneLevelName || '-'}
            </span>
          </>
        );
      },
    },
    rules: [
      {
        required: true,
        message: '请输入变更单号',
        trigger: 'change'
      }
    ],
    emit: ['change'],
  },
  {
    label: '是否提交',
    key: 'documentStatus',
    el: 'select',
    props: {
      placeholder: '请选择是否提交',
      options: [],
      fatch: (api) => {
        const list = [
          {
            label: '测试1',
            value: 1
          },
          {
            label: '测试2',
            value: 2
          }
        ]
        api.setFieldData && api.setFieldData({
          documentStatus: {
            options: list
          }
        })
      }
    },
    rules: [
      {
        required: true,
        message: '请选择是否提交',
        trigger: 'change'
      }
    ],
    on: {
      change: () => {
        console.log('------');

      }
    },
  },
  {
    key: 'remark',
    label: '备注',
    props: {
      disabled: true
    },
    rules: [
      {
        required: true,
        message: '请选择是否提交',
        trigger: 'change'
      }
    ],
    customRender: ({ value, update, disabled }: { value: any; update: (val: any) => void, disabled: boolean }) => (
      <div>
        <input
          placeholder="请输入备注---sdasda-"
          value={value}
          disabled={disabled}
          onChange={(e: any) => update(e.target.value)
          }
        />
      </div>
    ),
  },
  {
    el: 'tree-select',
    key: 'departId',
    label: '部门',
    props: {
      treeData: mockList,
    },
    renderSlots: {
      title: (option) => {
        return (
          <>
            <span style="float: left"> {option.label} </span>
            <span class=" float-right text-[13px] text-[#909399]" >
              部门：{option.oneLevelName}
            </span>
          </>
        );
      },
    },
    defaultValue: 'root 1',
  },
  {
    el: 'input',
    key: 'remark1',
    label: '环境',
    defaultValue: '测试',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark3',
    label: '郑航与',
    slot: true,
    rules: [
      {
        required: true,
        message: '请选择郑航与',
        trigger: 'change'
      }
    ],
  },
  // {
  //   el: 'MUpload',
  //   key: 'fileList',
  //   label: '上传文件',
  //   defaultValue: 'https://ts1.tc.mm.bing.net/th/id/R-C.22cdb21060f95297035a380467123768?rik=ZZ5YeI3loyMu0w&riu=http%3a%2f%2fimg.pconline.com.cn%2fimages%2fupload%2fupc%2ftx%2fwallpaper%2f1307%2f10%2fc0%2f23166997_1373443405186.jpg&ehk=UuR5odrdPxwmlbjY0C5WGXyxSJdyN%2b1aYi%2bnwiG6DPQ%3d&risl=&pid=ImgRaw&r=0',
  //   props: {

  //   },
  // }
])
const addFields = ref<Fields[]>([
  {
    label: '变更单号',
    key: 'orderNumber',
    el: 'select',
    props: {
      placeholder: '请输入变更单号',
      options: [
        {
          label: '是',
          value: 1,
          oneLevelName: '玉米'
        },
        {
          label: '否',
          value: 0,
          oneLevelName: '小麦'
        }
      ],
      showSearch: true,
      filterOption: (input: string, option: any) => {
        return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0
      }
    },
    renderSlots: {
      option: (option) => {
        return (
          <>
            <span style="float: left"> {option.label} </span>
            <span class=" float-right text-[13px] text-[#909399]">
              作物：{option.oneLevelName || '-'}
            </span>
          </>
        );
      },
    },
    rules: [
      {
        required: true,
        message: '请输入变更单号',
        trigger: 'change'
      }
    ],
    emit: ['change'],
  },
  {
    label: '是否提交',
    key: 'documentStatus',
    el: 'select',
    props: {
      placeholder: '请选择是否提交',
      options: [],
      fatch: (api) => {
        const list = [
          {
            label: '测试1',
            value: 1
          },
          {
            label: '测试2',
            value: 2
          }
        ]
        api.setFieldData && api.setFieldData({
          documentStatus: {
            options: list
          }
        })
      }
    },
    rules: [
      {
        required: true,
        message: '请选择是否提交',
        trigger: 'change'
      }
    ],
    on: {
      change: () => {
        console.log('------');

      }
    },
  },
  {
    key: 'remark',
    label: '备注',
    props: {
      readonly: true
    },
    rules: [
      {
        required: true,
        message: '请选择是否提交',
        trigger: 'change'
      }
    ],
    customRender: ({ value, update, disabled }: { value: any; update: (val: any) => void, disabled: boolean, readonly: boolean }) => (
      <div>
        <input
          placeholder="请输入备注---sdasda-"
          value={value}
          disabled={disabled}
          onChange={(e: any) => update(e.target.value)
          }
        />
      </div>
    ),
  },
  {
    el: 'tree-select',
    key: 'departId',
    label: '部门',
    props: {
      treeData: mockList,
    },
    renderSlots: {
      title: (option) => {
        return (
          <>
            <span style="float: left"> {option.label} </span>
            <span class=" float-right text-[13px] text-[#909399]" >
              部门：{option.oneLevelName}
            </span>
          </>
        );
      },
    },
    defaultValue: 'root 1',
  },
  {
    el: 'input',
    key: 'remark1',
    label: '环境',
    defaultValue: '测试',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark3',
    label: '郑航与',
    slot: true,
    rules: [
      {
        required: true,
        message: '请选择郑航与',
        trigger: 'change'
      }
    ],
  },
  {
    el: 'date-picker',
    key: 'maintenanceDate',
    label: '维护日期',
    rules: [
      {
        required: true,
        message: '请选择维护日期',
        trigger: 'change'
      }
    ],
  },
  {
    el: 'input',
    key: 'remark2',
    label: '备注',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark4',
    label: '备注',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark5',
    label: '备注',
    props: {
    },
    rules: [
      {
        required: true,
        message: '请选择郑航与',
        trigger: 'change'
      }
    ],
  },
  {
    el: 'input',
    key: 'remark6',
    label: '备注',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark7',
    label: '备注',
    props: {
    },
    rules: [
      {
        required: true,
        message: '请选择郑航与',
        trigger: 'change'
      }
    ],
  },
  {
    el: 'input',
    key: 'remark8',
    label: '备注',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark9',
    label: '备注',
    props: {
    }
  },
  {
    el: 'input',
    key: 'remark10',
    label: '备注',
    props: {
    },
    rules: [
      {
        required: true,
        message: '请选择郑航与',
        trigger: 'change'
      }
    ],
  },
  {
    el: 'input',
    key: 'remark11',
    label: '备注',
    props: {
    }
  },
  {
    el: 'MUpload',
    key: 'fileList',
    label: '上传文件',
    props: {

    },
  }
])
const formApi = ref()
const formEventApi = ref()
const submitTest = () => {
  formApi.value?.validate?.().then((res) => {
    console.log(res, 'res');

  }).catch(() => { })
}



onMounted(() => {
  // formEventApi.value.on('orderNumber-change', (data, opt, ...args) => {
  //   console.log(`表单1-字段变化:`, data, opt, args);
  // });
})


const clear = () => {
  formApi.value?.resetFormFields?.()
}

// <InstanceType<typeof VEditModal>>
const vEdieFormRef = ref()
const open = () => {
  vEdieFormRef.value?.showModal(0, false)
}

const addHttp = () => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve({ data: null, msg: 'ok', code: 200 })
    }, 1000)
  })
}

const reload = () => {
  console.log('reload');
}

const submit = (data) => {
  console.log(data, 'data');

}
const columns: any[] = [
  {
    title: '姓名',
    key: 'name',
    customRender: ({ record }) => {
      return (
        <div>
          <span>{record.name}</span>
          <a-tag color="blue">{record.age}</a-tag>
        </div>
      );
    }
  },
  {
    title: '年龄',
    key: 'age',
  },
  {
    title: '地址',
    key: 'address',
  },
  {
    title: '数量',
    key: 'quantity',
  },
  {
    title: '操作',
    key: 'action',
    width: 80
  },
];

const isReload = ref(false)
const selectedRowKeys = ref([])
// 模拟请求数据
const fetchTableData = async (params: any) => {
  console.log('请求参数:', params);
  // 模拟数据
  return new Promise((resolve) => {
    setTimeout(() => {
      const data: any[] = [];
      const { page = 1, pageSize = 10 } = params;

      for (let i = 0; i < pageSize; i++) {
        data.push({
          id: (page - 1) * pageSize + i + 1,
          name: `用户${(page - 1) * pageSize + i + 1}`,
          age: 20 + Math.floor(Math.random() * 20),
          address: `地址${(page - 1) * pageSize + i + 1}`,
          quantity: Math.floor(Math.random() * 100),
          // status: i 为 偶数， 值为 1， 为 奇数， 值为 2
          status: i % 2 === 0 ? 1 : 2,
        });
      }
      resolve({
        data: {
          record: data,
          total: 100,
        },
        msg: 'ok',
        code: 200
      });
    }, 500);
  });
};

const permissions = ref(['admin:edit', 'admin:delete', 'admin:add'])
const formConfig = {
  offset: 300
}
</script>

<template>
  <MConfigProvide v-bind="{
    tableConfig: {
      transform: (data: any) => ({
        data: data.data.record,
        total: data.data.total
      }),
      transformParams: (params: any) => ({
        page: params.current,
        pageSize: params.pageSize
      })
    }
  }">
    <MForm v-model:api="formApi" :fields="fields" search :formOptions="{ layout: 'inline' }" formId="search-form">
      <template #remark3="{ value, setValue }">
        <input style="width: 100%;" :value="value" @change="(e: any) => setValue(e.target && e.target.value)" placeholder="请输入备注" />
      </template>
    </MForm>
    <!-- <a-button @click="submitTest">提交</a-button>
  <a-button @click="clear">清除</a-button> -->

    <a-button @click="open">打开弹窗</a-button>
    <MEditModal ref="vEdieFormRef" :fields="addFields" formId="edit-form" :httpAdd="addHttp" :form-config="formConfig"
      @reload="reload">
      <template #remark3="{ value, setValue, disabled }">
        <input style="width: 100%;" :disabled="disabled" :value="value" @change="(e: any) => setValue(e.target && e.target.value)"
          placeholder="请输入备注" />
      </template>
    </MEditModal>
    <!-- <CAUpload v-model:value="fileList" :accept="['.png', '.jpg', '.jpeg']"></CAUpload> -->
    {{ selectedRowKeys }}
    <MTable v-model:isReload="isReload" v-model:selected-row-keys="selectedRowKeys" :columns="columns" :row-selection="true" :request="fetchTableData" :showIndex="true" :summary-columns="['age', 'quantity']" show-summary
      summary-text="统计">
      <template #menuAction>
        <a-button type="primary">新增</a-button>
      </template>
      <template #action>
        <a-button>修改</a-button>
      </template>
    </MTable>

    <!-- 动态删除元素 -->
    <a-button v-permission="'user:add'">新增</a-button>
    <!-- css样式隐藏：元素依然存在 -->
    <!-- <a-button v-permission.hide="'admin:edit'">修改</a-button> -->
    <!-- 单纯的禁用 -->
    <!-- <a-button v-permission.disable="['admin:delete']">删除</a-button> -->
  </MConfigProvide>
</template>

<style>
#app {
  height: 100%;
  width: 100%;
  padding: 0;
  margin: 0
}
</style>
